<?php

namespace app\common\controller;

use app\admin\controller\cms\MembershipExpiryRecord;
use app\admin\model\cms\AlbumModel;
use app\admin\model\cms\Channels;
use app\admin\model\cms\Diyform;
use app\admin\model\cms\Live;
use app\admin\model\cms\LiveCategoryModel;
use app\admin\model\cms\MembershipExpiryRecordModel;
use app\admin\model\cms\Plate;
use app\admin\model\cms\Platepost;
use app\admin\model\cms\PlazaCategorymodel;
use app\admin\model\cms\PlazaPostModel;
use app\admin\model\cms\Video;
use app\admin\model\cms\VideoCategoryModel;
use app\admin\model\Column;
use app\admin\model\InvestmentCategoryModel;
use app\admin\model\User;
use app\common\library\Auth;
use app\common\model\ChartParent;
use think\Config;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Model;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;

/**
 * API控制器基类
 */
class Api
{

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        //跨域请求检测
        check_cors_request();

        // 检测IP是否允许
        check_ip_allowed();

        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');

        $this->auth = Auth::instance();

        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());

        $_token  = empty($this->request->request('token'))? Request()->header('token') : $this->request->request('token', \think\Cookie::get('token'));
		
        // token
        $token = $this->request->server('HTTP_TOKEN', $_token);
		
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $this->error(__('Please login first'), $this->request->param(), 401);
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error(__('You have no permission'), null, 403);
                }
            }
        } else {
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $this->auth->init($token);
            }
        }

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 加载当前控制器语言包
        $this->loadlang($controllername);
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $name = Loader::parseName($name);
        $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
        $lang = $this->request->langset();
        $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
        exit();
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
        exit();
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 前置操作
     * @access protected
     * @param string $method  前置操作方法名
     * @param array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
     * @param array        $data     数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array        $message  提示信息
     * @param bool         $batch    是否批量验证
     * @param mixed        $callback 回调方法（闭包）
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = Loader::validate();
            $v->rule($validate);
        } else {
            // 支持场景
            if (strpos($validate, '.')) {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        // 设置错误信息
        if (is_array($message)) {
            $v->message($message);
        }
        // 使用回调验证
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->param('__token__');

        //验证Token
        if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
            $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
        }

        //刷新Token
        $this->request->token();
    }

    /**
     * 获取开始结束时间
     * @param $type 1:今日,2:七日内发布的内容,3:本月发布的,4:今年发布的
     */
    protected function getStartAndEndTime($type){
        //1:今日,2:七日内发布的内容,3:本月发布的,4:今年发布的
        switch ($type) {
            case 1:
                $start_time = date('Y-m-d 00:00:00');
                break;
            case 2:
                $start_time = date('Y-m-d', strtotime('-7 days'));
                break;
            case 3:
                $start_time = date('Y-m-d', strtotime('-1 month'));
                break;
            case 4:
                $start_time = date('Y-m-d', strtotime('-1 year'));
                break;
            default:
                $start_time = date('Y-m-d', strtotime('-1 year'));
        }
        $end_time = date('Y-m-d 23:59:59');
        return [
            'start_time'=>$start_time,
            'end_time'=>$end_time,
        ];
    }

    /**
     * 检测用户是否购买相关内容会员
     * 最新检测购买权限方法
     * @param $user_id 用户id
     * @param $goods_id 商品相关id|table_name表名下的id值
     * @param $table_name 商品来源的表名|不带表名前缀
     * @param $category_id 商品来源的表名下的 ???_live_category_id 分类id关联字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function hasMembershipExpiryRecordArticles($user_id, $table_name, $goods_id, $category_id)
    {
        $time = time();
        $res = [
            'code' => 200,
            'msg' => 'success',
        ];

        //判断当前分类id是否存在当前会员权限中
        $user = User::where('id',$user_id)->find();

        //不在会员权限分组里面的情况
        //判断栏目是否收费
        switch ($table_name) {
            case 'plate_post':
                $category_membership_price = Plate::where('id', $category_id)->value('membership_price') ?? 0;
                $categories_table_name = 'plate';
                $articles_membership_price = Platepost::where('id', $goods_id)->value('membership_price') ?? 0;
                $channels_id = Channels::where('parent_id',2)
                    ->where('correlation_id', $category_id)
                    ->value('id');
                break;
            case 'plaza_post':
                $category_membership_price = PlazaCategorymodel::where('id', $category_id)->value('membership_price') ?? 0;
                $categories_table_name = 'plaza_category';
                $articles_membership_price = PlazaPostModel::where('id', $goods_id)->value('membership_price') ?? 0;
                $channels_id = Channels::where('parent_id',1)
                    ->where('correlation_id', $category_id)
                    ->value('id');
                break;
            case 'live':
                $category_membership_price = LiveCategoryModel::where('id', $category_id)->value('membership_price') ?? 0;
                $categories_table_name = 'live_category';
                $articles_membership_price = Live::where('id', $goods_id)->value('membership_price') ?? 0;
                $channels_id = Channels::where('parent_id',6)
                    ->where('correlation_id', $category_id)
                    ->value('id');
                break;
            case 'video':
                $category_membership_price = VideoCategoryModel::where('id', $category_id)->value('membership_price') ?? 0;
                $categories_table_name = 'video_category';
                $articles_membership_price = Video::where('id', $goods_id)->value('membership_price') ?? 0;
                $channels_id = Channels::where('parent_id',4)
                    ->where('correlation_id', $category_id)
                    ->value('id');
                break;
            case 'album':
                $category_membership_price = VideoCategoryModel::where('id', $category_id)->value('membership_price') ?? 0;
                $categories_table_name = 'video_category';
                $articles_membership_price = AlbumModel::where('id', $goods_id)->value('membership_price') ?? 0;
                $channels_id = Channels::where('parent_id',4)
                    ->where('correlation_id', $category_id)
                    ->value('id');
                break;
            case 'investment':
                $category_membership_price = InvestmentCategoryModel::where('id', $category_id)->value('membership_price') ?? 0;
                $categories_table_name = 'investment_category';
                $articles_membership_price = 0;
                $channels_id = Channels::where('parent_id',7)
                    ->where('correlation_id', $category_id)
                    ->value('id');
                break;
            case 'chart_parent':
                $category_membership_price = ChartParent::where('id', $category_id)->value('membership_price') ?? 0;
                $categories_table_name = 'chart_parent';
                $articles_membership_price = 0;//图表没有内容会员,要买只能买单个分类或会员组
                $channels_id = Channels::where('parent_id',4)
                    ->where('correlation_id', $category_id)
                    ->value('id');
                break;
            default:
        }

        $new_user = new User();
        $rule_column_id = $new_user->isChannelsPermission($user)['rule_column_id'];//当前用户拥有权限的的全部栏目id含2级栏目
        if (in_array($channels_id,$rule_column_id)){
            return $res;
        }


        $is_auth = true;//是否授权
        $membershipExpiryRecord = new \app\api\controller\v2\MembershipExpiryRecord();
        //栏目收费
        if ((float)($category_membership_price) >= 0.01) {
            $isMemberExpire = $membershipExpiryRecord->isMemberExpire($user['id'], 'categories', $categories_table_name, $category_id);//判断会员购买的分类权限是否到期
            if ($isMemberExpire['code'] != 200) {
                $is_auth = false;//是否授权
            }else{
                return $res;
            }
        }


        //内容收费
        if ((float)$articles_membership_price >= 0.01) {
            //判断是内容还是专辑
            if ($table_name == 'album') {
                $goods_type = 'album';
            } else {
                $goods_type = 'articles';
            }
            $isMemberExpire = $membershipExpiryRecord->isMemberExpire($user['id'], $goods_type, $table_name, $goods_id);
            //判断开没开内容会员
            if ($isMemberExpire['code'] != 200) {
                $is_auth = false;//是否授权
            }else{
                return $res;
            }
        }

        //这是$is_auth=true 有2种情况 1:分类/内容就是免费的,2:用户没权限
        if ($is_auth){
            return $res;
        }else{
            $res['code'] =500;
            $res['msg'] = '没有访问权限';
            return $res;
        }
    }

    //Markdown 转 富文本html
    protected function markdownToHtml($string){
        // 替换图片链接
        $string = preg_replace_callback('/!\[Image Description\]\((.*?)\)/', function($matches) {
            return '<img src="' . obsurl($matches[1]) . '">';
        }, $string);

// 替换视频链接
        $string = preg_replace_callback('/\[Video Link\]\((.*?)\)/', function($matches) {
            return '<video src="' . obsurl($matches[1]) . '" controls></video>';
        }, $string);

// 替换下载链接
        $string = preg_replace_callback('/\[Download Attachment\]\((.*?)\)/', function($matches) {
            $file_name = basename($matches[1]);
            return '<p><a href="' . obsurl($matches[1]) . '" download>' . $file_name . '</a></p>';
        }, $string);

// 替换文本内容
        $string = preg_replace('/(.+?)(\n|$)/', '<p>$1</p>', $string);
        return $string;// 输出HTML富文本字符串
    }


}
